package com.lujieni.seataorder.controller;

import com.lujieni.seataorder.po.OrderPO;
import com.lujieni.seataorder.dao.OrderPOMapper;
import com.lujieni.seataproxy.PayFeign;
import com.lujieni.seataproxy.dto.PayDTO;
import io.seata.spring.annotation.GlobalLock;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
public class OrderController {

    @Autowired
    private OrderPOMapper orderPOMapper;
    @Autowired
    private PayFeign payFeign;

    /**
     * 1.GlobalTransactional注解加在事务发起者上即可,别的分支事务上不需要加
     * 2.如果方法只作为全局事务的一部分的话不需要加Transactional注解,seata会自动
     *   帮你补偿事务,即使有多条sql语句也同样会回滚
     * 3.seata中A服务调用B服务,B服务再去调用C服务 分布式事务也能生效
     * 4.at模式下业务数据的更新和undolog日志一并提交(本地事务)
     * 5.本地事务提交前会先获取全局锁,获取不到的话会等待,等待也不行就回滚
     * 6.seata的at模式会有脏写的问题,解决方法可以加@GlobalTransactional或者GlobalLock
     */
    @GetMapping(value = "/addOrder")
    @GlobalTransactional(rollbackFor = Exception.class)
    public void order() {
        OrderPO orderPO = new OrderPO();
        orderPO.setId(1L);
        orderPO.setAmount(BigDecimal.valueOf(12.34));
        orderPO.setUserId(100L);
        orderPO.setActive(1);
        orderPOMapper.insert(orderPO); //先提交本地提交并取得全局锁
        PayDTO payDTO = new PayDTO();
        BeanUtils.copyProperties(orderPO, payDTO);
        payFeign.addPay(payDTO);
    }

    @GetMapping(value = "/deleteOrder")
    @GlobalLock(lockRetryTimes = 1,lockRetryInterval = 10)
    public void deleteOrder(){
        orderPOMapper.deleteByPrimaryKey(1L);
    }


}
